<!--
 * @Author: your name
 * @Date: 2020-04-14 14:07:25
 * @LastEditTime: 2020-06-12 20:12:32
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-element-admin\src\views\enterprise\troubleDetail.vue
 -->
<template>
  <div class="app-container">
    <el-form ref="postForm" :model="postForm" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-input v-model="postForm.id" type="hidden"></el-input>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="115px" label="所属单位" class="postInfo-container-item">
                    <el-select v-model="postForm.companyId" placeholder="所属单位" clearable>
                      <el-option
                        v-for="item in enterpriseList"
                        :key="item.companyId"
                        :label="item.companyName"
                        :value="item.companyId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="115px" label="隐患级别" class="postInfo-container-item">
                    <el-select v-model="postForm.dangerLevel" placeholder="请选择隐患级别">
                      <el-option
                        v-for="item in troubleGrades"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="115px" label="隐患名称" class="postInfo-container-item">
                    <el-input placeholder="请输入隐患名称" v-model="postForm.dangerName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="115px" label="隐患描述" class="postInfo-container-item">
                    <el-input
                      placeholder="请输入隐患描述"
                      v-model="postForm.dangerContent"
                      type="textarea"
                      :rows="4"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :span="24">
                  <el-form-item label-width="115px" label="已上传照片" class="postInfo-container-item">
                    <ele-gallery :source="postForm.pics" :removeFn="this.deleteUploadImage"></ele-gallery>
                  </el-form-item>
                </el-col>
              </el-row>-->
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="115px" label="隐患照片上传" class="postInfo-container-item">
                    <el-upload
                      class="upload-demo"
                      action="#"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :file-list="postForm.pics"
                      list-type="picture"
                      :http-request="httpRequest"
                    >
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="115px" label="整改类型" class="postInfo-container-item">
                    <el-select
                      v-model="postForm.dangerRecitfyType"
                      placeholder="整改类型"
                      clearable
                      class="filter-item"
                    >
                      <el-option
                        v-for="item in troubleRectifyTypes"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="postForm.dangerRecitfyType==2">
                  <el-form-item label-width="115px" label="整改期限" class="postInfo-container-item">
                    <el-date-picker
                      v-model="postForm.recitfyOverdate"
                      type="date"
                      value-format="yyyy/MM/dd"
                      placeholder="请输入整改期限"
                      class="filter-item"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="115px" label="整改要求" class="postInfo-container-item">
                    <el-input
                      placeholder="请输入整改要求"
                      v-model="postForm.recitfyRequirement"
                      type="textarea"
                      :rows="4"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button type="primary" @click="submitForm(1)">保存草稿</el-button>
                    <el-button type="primary" @click="submitForm(2)">正式发布</el-button>
                    <el-button @click="closeCurrentTag">关闭</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
<script>
import { validURL, validUsername } from '@/utils/validate'
import { fetchList as fetchEnterpriseList } from '@/api/enterprise'
import { editTrouble, fetchTroubleDetail } from '@/api/troubles'
import { getBaseDicInfo } from '@/api/baseApi'
import EleGallery from 'vue-ele-gallery'
export default {
  created() {
    this.getTroubleGradesList()
    this.getRectifyTypeList()
    this.getEnterpriseList()
    // if (this.isEdit) {
    //如果是编辑数据
    const id = this.$route.params && this.$route.params.id
    this.getTroubleDetail(id)
    // }
    this.tempRoute = Object.assign({}, this.$route)
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  components: {
    // EleGallery
  },
  data() {
    return {
      // imgfileList: [],
      troubleGrades: [], //隐患级别
      troubleRectifyTypes: [], //整改类型
      enterpriseList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      loading: false,
      postForm: {
        id: '',
        companyId: '',
        dangerLevel: '',
        dangerName: '',
        dangerContent: '',
        dangerState: '',
        dangerRecitfyType: '',
        recitfyOverdate: '',
        recitfyRequirement: '',
        dangerAppendixCrudeFileIds: [],
        dangerAppendixUpdateFileIds: [],
        fileList: [],
        pics: []
      }
    }
  },

  methods: {
    closeCurrentTag() {
      // 调用全局挂载的方法
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由
      this.$router.go(-1)
    },
    getTroubleDetail(id) {
      fetchTroubleDetail({
        dangerId: id,
        pType: 2
      }).then((response) => {
        this.troubleDetail = response.data
        // console.log('this.troubleDetail', this.troubleDetail)

        this.postForm = {
          id: this.troubleDetail.id,
          companyId: this.troubleDetail.companyId,
          dangerLevel: this.troubleDetail.dangerLevel,
          dangerName: this.troubleDetail.dangerName,
          dangerContent: this.troubleDetail.dangerContent,
          dangerState: this.troubleDetail.dangerState,
          dangerRecitfyType: this.troubleDetail.dangerRecitfyType,
          recitfyOverdate: this.troubleDetail.recitfyOverdate,
          recitfyRequirement: this.troubleDetail.recitfyRequirement,
          dangerAppendixCrudeFileIds: this.troubleDetail
            .dangerAppendixCrudeFileIds,
          dangerAppendixUpdateFileIds: this.troubleDetail
            .dangerAppendixUpdateFileIds,
          pics: this.handlePics(this.troubleDetail.dangerAppendixObjs),
          fileList: []
        }
      })
    },
    handlePics(pics) {
      return pics.map((p) => {
        p.url = `/api${p.url}`
        return p
      })
    },
    deleteUploadImage(obj) {
      // console.log('88888888888888888', obj)
    },
    submitForm(dangerState) {
      const formData = new FormData()
      formData.append('id', this.postForm.id)
      formData.append('companyId', this.postForm.companyId)
      formData.append('dangerLevel', this.postForm.dangerLevel)
      formData.append('dangerName', this.postForm.dangerName)
      formData.append('dangerContent', this.postForm.dangerContent)
      formData.append('dangerRecitfyType', this.postForm.dangerRecitfyType)
      formData.append('recitfyOverdate', this.postForm.recitfyOverdate)
      formData.append('recitfyRequirement', this.postForm.recitfyRequirement)
      formData.append(
        'dangerAppendixCrudeFileIds',
        this.postForm.dangerAppendixCrudeFileIds
      )
      formData.append(
        'dangerAppendixUpdateFileIds',
        this.postForm.dangerAppendixUpdateFileIds
      )
      formData.append('dangerState', dangerState)
      this.postForm.fileList.forEach((file) => {
        formData.append('files', file, file.name)
      })
      // formData.append('file', this.postForm.file)
      // for (var key of formData.keys()) {
      //   console.log('key:' + key + ' value:' + formData.get(key))
      // }
      this.$confirm('此操作将确认编辑隐患, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          editTrouble({ formData }).then((res) => {
            if (res.success) {
              this.$notify({
                title: '成功',
                message: '编辑隐患成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '编辑隐患失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          })
        })
    },
    getEnterpriseList() {
      fetchEnterpriseList({ pageIndex: 1, limit: 10 }).then((response) => {
        // console.log(response.data)
        this.enterpriseList = response.data.records
      })
    },
    // 上传之前的格式设置
    beforeAvatarUpload(file) {
      //图片上传前图片大小和类型判断
      const isImg = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      // const isSize = file.size / 1024 / 1024 < 1
      if (!isImg) {
        this.$message.error('上传文件只能是图片格式！')
      }
      // if (!isSize) {
      //   this.$message.error('上传图片不能超过1MB！')
      // }
      // return isImg && isSize
      return isImg
    },
    httpRequest(data) {
      // console.log('httprequest')
      // console.log('data.file', data.file)
      this.postForm.fileList.push(data.file)
      // console.log('this.postForm.fileList', this.postForm.fileList)
    },
    // fileChange(file) {
    //   // console.log('fileChange')
    //   // this.postForm.pics.push({
    //   //   name: file.name,
    //   //   url: file.url
    //   // })
    // },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      //此处file表示被删除的文件
      this.postForm.dangerAppendixUpdateFileIds = fileList.map((file) => {
        if (!file.raw) {
          return file.id
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getTroubleGradesList() {
      getBaseDicInfo({ typeId: 2 }).then((response) => {
        this.troubleGrades = response.data
      })
    },
    getRectifyTypeList() {
      getBaseDicInfo({ typeId: 1 }).then((response) => {
        this.troubleRectifyTypes = response.data
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.fieldInfo {
  border-color: #eee;
  border-width: 1px;
  border-style: solid;
  margin-bottom: 20px;
  legend {
    color: #666;
  }
}
</style>
